const express = require("express");
const cors = require("cors");
const { testConnection } = require("./config/database");
require("dotenv").config();
const passport = require("./config/passport");
const session = require("express-session");
const path = require("path");
const bodyParser = require('body-parser');
const stripeController = require('./controllers/stripeController');
const tokenCleanupTask = require('./utils/tokenCleanupTask');
const http = require('http');
const socketIo = require('socket.io');
const chatSocketManager = require('./utils/chatSocketManager');

// 路由导入
const visitorRoutes = require("./routes/visitorRoutes");
const aiPersonRoutes = require("./routes/aiPersonRoutes");
const adminRoutes = require("./routes/adminRoutes");
const authRoutes = require("./routes/authRoutes");
const minMaxRoutes = require("./routes/minMaxRoutes");
const userRoutes = require("./routes/users");
const stripeRoutes = require("./routes/stripe"); //支付
const voiceforTextRoutes = require("./routes/voiceforTextRoutes"); //腾讯云语音识别签名颁发接口
const aiChatRoutes = require("./routes/AiChatRoutes"); //AI聊天功能
const tokenRoutes = require("./routes/tokenRoutes"); //代币管理
const ossRoutes = require("./routes/ossRoutes"); //OSS文件管理
const chatRoutes = require("./routes/chatRoutes"); //聊天历史管理
const aiPersonImageRoutes = require("./routes/AiPersionImageRoutes"); //AI图片生成管理

// 初始化Express应用
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: '*',
    methods: ['GET', 'POST']
  }
});
const PORT = process.env.PORT || 3000;

// 将io实例存储到app，使其可在路由中使用
app.set('io', io);

// Stripe支付回调 必须放在 express.json() 之前
app.post('/api/stripe/webhook', bodyParser.raw({type: 'application/json'}), stripeController.handleWebhook);

// 中间件配置
app.use(cors()); // 启用CORS
app.use(express.json({ limit: '50mb' })); // 解析JSON请求体，支持大文件上传
app.use(express.urlencoded({ extended: true, limit: '50mb' })); // 解析URL编码的请求体，支持大文件上传

// 静态文件服务
app.use(express.static(path.join(__dirname, "../public")));

// 配置会话
app.use(
  session({
    secret: process.env.JWT_SECRET,
    resave: false,
    saveUninitialized: false,
    cookie: { secure: process.env.NODE_ENV === "production" },
  })
);

// 初始化Passport
app.use(passport.initialize());
app.use(passport.session());

// 简单的请求记录中间件
app.use((req, res, next) => {
  // console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next();
});

// 注册路由
app.use("/api/visitor", visitorRoutes);
app.use("/api/ai-persons", aiPersonRoutes);
app.use("/api/admin", adminRoutes);
app.use("/auth", authRoutes);
app.use("/api/minmax", minMaxRoutes); 
app.use("/api/users", userRoutes);
app.use("/api/stripe", stripeRoutes); //支付功能
app.use("/api/voiceforText", voiceforTextRoutes); //腾讯云语音识别签名颁发接口
app.use("/api/ai-chat", aiChatRoutes); //AI聊天功能
app.use("/api/tokens", tokenRoutes); //代币管理
app.use("/api/oss", ossRoutes); //OSS文件管理
app.use("/api/chat", chatRoutes); //聊天历史管理
app.use("/api/ai-person-image", aiPersonImageRoutes); //AI图片生成管理

// 根路由 - API状态检查
app.get("/", (req, res) => {
  res.json({
    status: "online",
    message: "游客认证服务API正在运行",
    version: "1.0.0",
    timestamp: new Date().toISOString(),
  });
});

// 捕获404错误 - 未找到的路由
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: "请求的资源不存在",
  });
});

// 全局错误处理中间件
app.use((err, req, res, next) => {
  console.error("全局错误:", err);
  res.status(500).json({
    success: false,
    message: "服务器内部错误",
    error: process.env.NODE_ENV === "development" ? err.message : undefined,
  });
});

// 启动服务器
const startServer = async () => {
  try {
    // 测试数据库连接并同步模型
    await testConnection();

    // 启动服务器
    server.listen(PORT, () => {
      console.log(`服务器正在运行，端口: ${PORT}`);
      // console.log(`API地址: http://localhost:${PORT}`);
      console.log(`环境: ${process.env.NODE_ENV}`);
      console.log('WebSocket服务已启动');

      // 输出代理配置状态
      const proxyStatus =
        process.env.USE_PROXY === "true"
          ? `已启用, ${process.env.PROXY_PROTOCOL}://${process.env.PROXY_HOST}:${process.env.PROXY_PORT}`
          : "已禁用";
      console.log(`代理配置: ${proxyStatus}`);

      // 启动代币清理定时任务
      tokenCleanupTask.start();
      console.log('代币过期清理任务已启动');
    });
    
    // 设置WebSocket连接
    io.on('connection', (socket) => {
      console.log('新的WebSocket连接已建立:', socket.id);
      
      // 处理用户认证
      socket.on('authenticate', (data) => {
        if (data && data.uuid) {
          console.log(`用户认证: ${data.uuid}`);
          // 将socket关联到用户的UUID
          socket.join(data.uuid);
          socket.emit('authenticated', { success: true });
        }
      });
      
      // 处理聊天历史订阅
      socket.on('subscribe-chat-history', (data) => {
        if (data && data.uuid) {
          const room = `chat-history-${data.uuid}`;
          console.log(`订阅聊天历史: ${room}`);
          socket.join(room);
          socket.emit('subscribed-chat-history', { success: true });
        }
      });
      
      socket.on('disconnect', () => {
        console.log('WebSocket连接已断开:', socket.id);
      });
    });
    
    // 初始化聊天WebSocket管理器
    chatSocketManager.initialize(io);
  } catch (error) {
    console.error("启动服务器失败:", error);
    process.exit(1);
  }
};

// 优雅关闭处理
process.on('SIGTERM', () => {
  console.log('收到 SIGTERM 信号，正在关闭服务器...');
  tokenCleanupTask.stop();
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('收到 SIGINT 信号，正在关闭服务器...');
  tokenCleanupTask.stop();
  process.exit(0);
});

// 启动应用
startServer();
